package cn.szabadsag.hrm.config;

import cn.szabadsag.hrm.domain.Permission;
import cn.szabadsag.hrm.handler.MyAuthenticationFailureHandler;
import cn.szabadsag.hrm.handler.MyAuthenticationSuccessHandler;
import cn.szabadsag.hrm.mapper.PermissionMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.EnableGlobalAuthentication;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.util.List;

@Slf4j
@Configuration
@EnableWebSecurity
//  开启全局方法授权注解支持
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private MyAuthenticationSuccessHandler successHandler;

    @Autowired
    private MyAuthenticationFailureHandler failureHandler;

    @Autowired
    private PermissionMapper permissionMapper;

    //密码编码器：不加密
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    //授权规则配置
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        /*
        //  查询用户所有的权限
        List<Permission> permissions = permissionMapper.selectList(null);

        //  循环加载用户的权限
        permissions.forEach(permission -> {
            try {
                log.info("加载系统权限 {} - {}", permission.getResource(), permission.getSn());
                http.authorizeRequests()
                        .antMatchers(permission.getResource())
                        .hasAuthority(permission.getSn());
            } catch (Exception e) {
                e.printStackTrace();
            }
        });*/

        http.authorizeRequests()                                //授权配置
                /*.antMatchers("/login",
                        "/vipUser/register",
                        "/vipUser/changePassword",
                        "/loginUser/userMeals",
                        "/loginUser/uptPassword",
                        "/loginUser/login"
                        ).permitAll()  //登录路径放行*/
                .antMatchers("/**").permitAll()
                .anyRequest().authenticated()                   //其他路径都要认证之后才能访问
                .and().formLogin()                              //允许表单登录
                .successHandler(successHandler)   //  认证成功处理器
                .failureHandler(failureHandler)   //  认证失败处理器
                //.successForwardUrl("/loginUser/loginSuccess")             // 设置登陆成功页
                .and().logout().permitAll()                    //登出路径放行 /logout
                .and().csrf().disable();                        //关闭跨域伪造检查
    }

    //配置认证管理器，授权模式为“password”时会用到
    @Bean
    public AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

}
